/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","jqprint","fu/app/comm/comm","fu/app/comm/validate","fu/app/comm/attention",
	"scprit/followup/app/outPatient/outPatient.ui.js",
	"scprit/followup/app/outPatient/outPatient.servers.js",
	"scprit/followup/app/question/question.ui.js",
	"scprit/followup/app/question/question.event.js"
	],function($,$bb,$jqprint,$comm,$validate,$attention,$outPatientUi,$outPatientServers,$questionUi,$questionEvent){
	var event = {};
	var clickTaskFlag = false; //默认false，当点击了task-babycard名片时，变为true；

	/**
	 * 选择初选小结其中一个图片
	 */
	var onPictureSelect = function(){
		$(this).addClass("active").siblings().removeClass("active");
		var h = $(window).height() - 221;
		$(".discharge-summary .picture").css({"height":h});
		var url = $(this).children("img").attr("src");
		var $picBox = $(".discharge-summary .picture");
		var $img = $(".discharge-summary .picture img");
		$img.css({"marginTop":0}).unbind("load");
		$img.attr("src",url).load(function(){
			if( $img.height() > 0 && $img.height() < h ){
				var top = ( h - $img.height() ) / 2;
				$img.css({"marginTop":top});
			}
		});
		/*$("<img/>").attr("src", url).load(function() {
			var This = this;
			if( This.width >= $img.width() ){
				$img.addClass("zoom-in").css({"width":$picBox.width()}).unbind("click");
				// 放大
				$img.click(function(){
					if( This.width > $img.width() ){
						$img.css({"width":$img.width() + 100});
					}else{
						$img.css({"width":This.width});
					}
				});
			}else{
				$img.removeClass("zoom-in");
			}
		});*/
	}

	/**
	 * 翻页
	 */
	var onPageClick = function(){
		var datas = $(this).data("datas");
		if( datas.type == "-1" ){
			datas.arg.page--;
		}else{
			datas.arg.page++;
		}
		$outPatientServers.ajaxNffyyFile(datas.arg,ajaxNffyyFileCallBack,datas.className);
	}

	/**
	 * 根据文件的一个地址请求文件的另一个地址成功后的回调函数
	 */
	var ajaxImgFileSignUrlCallBack = function(data,arg,total,className){
		$outPatientUi.dischargeSummary({
			"dom":$("." + className + " .modal-body"),
			"list":data.fileList,
			"pages":Math.ceil(total / arg.rows),
			"page":arg.page
		});
		$("." + className).modal("show");
		$("." + className + " .discharge-summary .list li").unbind("click");
		$("." + className + " .discharge-summary .list li").click(onPictureSelect);
		$("." + className + " .discharge-summary .list li").eq(0).click();
		$("." + className + " .discharge-summary .list .arrow-left").unbind("click");
		$("." + className + " .discharge-summary .list .arrow-left").data("datas",{"arg":arg,"className":className,"type":"-1"});
		$("." + className + " .discharge-summary .list .arrow-left").click(onPageClick);
		$("." + className + " .discharge-summary .list .arrow-right").unbind("click");
		$("." + className + " .discharge-summary .list .arrow-right").data("datas",{"arg":arg,"className":className,"type":"1"});
		$("." + className + " .discharge-summary .list .arrow-right").click(onPageClick);
	}

	/**
	 * 请求绑定在该患者身上的图片成功后的回调函数
	 */
	var ajaxNffyyFileCallBack = function(data,arg,className){
		if( data.rows.length > 0 ){
			var fileList = [];
			for (var i = 0; i < data.rows.length; i++) {
				var obj = {};
				obj.imgUrl = data.rows[i].filePath;
	        	obj.imgId = data.rows[i].id;
	        	fileList.push(obj);
			}
			var params = {
		        "channel": "BBCARE-APP",
		        "fileList": fileList
		    };
			$outPatientServers.ajaxImgFileSignUrl(params,ajaxImgFileSignUrlCallBack,arg,data.total,className);
		}else{
			$bb.toastShow("患者未上传出院小结！");
		}
	}

	/**
	 * 出院小结
	 */
	var onLookPicture = function(){
		var oprInfo = $(this).data("params").oprInfo;
		var className = "dischargeSummaryModal";
		$bb.modal({
			"className":className,
			"size":"modal-lg",
			"tit":"出院小结（图片）",
		},function(){
			var params = {
				"schemeBusiType":"1",
				"ptSchemeId":oprInfo.ptSchemeId,
				"userId":oprInfo.patientId,
				"page":1,
				"rows":6
			};
			$outPatientServers.ajaxNffyyFile(params,ajaxNffyyFileCallBack,className);
		});
	}

	/**
	 * 审核
	 */
	var onCheckClick = function(){
		var data = $(this).data("params");
		$bb.toastConfirmShow(function(){
			if( $validate.init() ){
				$outPatientServers.ajaxSaveQuestion(data.data,data.params,data.curInfo,getSaveCallback);
			}
		},data,"审核通过？");
	}
	
	/**
	 * 刷新任务列表UI
	 */
	var refreshTasksUi = function(rows,curInfo){
		$outPatientUi.showContainerInit({
			id:"showContainer",
			list: rows,
			taskId: curInfo.taskId,  // 从随访记录中跳过来，带过来的 taskId,(目的：当前标记，背景变绿)
		});
		if(curInfo.taskId === rows[0].taskId){
			$(".show-wrapper > div.row").eq(0).addClass("active").siblings().removeClass("active");
		}
		$(function(){
		  	$('[data-toggle="tooltip"]').tooltip();
		});
	};
	/**
	 * 请求医院的信息成功后的回调函数(打印时需要)
	 */
	var handlePrintHospitalCallBack = function(hospital,info,data){
		$outPatientUi.printInit({
        	"id":"printContent",
        	"info":info,
        	"data":data,
        	"hospital":hospital
        });
        $("#printContent").jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        });
        return;
	}
	/**
	 * 点击打印按钮
	 */
	var onPrintClick = function(event){
		var This = $(this);
		var h1 = '<i class="fa fa-print"></i>打印'; 
		var h2 = '<i class="fa fa-print"></i>打印中'; 
		if( This.html() == h1 ){
			This.html(h2).addClass("cursor-not-allowed");
			setTimeout(function(){
				This.html(h1).removeClass("cursor-not-allowed");
				$("body iframe.jqprint").remove();
			},2000);
			var data = This.data("params");
			var ageLabel = $("#followupAge > label").text();
			if($("#followupAge p").length > 0){
				var age = $("#followupAge p").text();
			}else{
				var age = $("#followupAge input").val();
			}
			$.extend(data.params,{"age":age,"ageLabel":ageLabel});
			$outPatientServers.handlePrintHospital(data.params,data.data,handlePrintHospitalCallBack);
		}
	}
	/**
	 * navbar点击左右箭头进行滚动
	 */
	var onNavbarRoll = function($arrLeft,$arrRight,$wrapper,showNum,w,len,i,showWidth){
		$arrLeft.unbind("click"); //先解除绑定事件,绑定新事件
		$arrLeft.click(function(){
			if( clickTaskFlag ){
				clickTaskFlag = false;
				i = 0;
			}
			if( i >= showNum ){
				i--;
				$wrapper.stop().animate({ marginLeft: -w*(i+1-showNum) });
			}
		});
		$arrRight.unbind("click");
		$arrRight.click(function(){
			if( clickTaskFlag ){
				clickTaskFlag = false;
				i = 0;
			}
			if( i < showNum - 1 ) i = showNum - 1;
			if( i <= len - 3 ){
				i++;
				$wrapper.stop().animate({ marginLeft: -w*(i+1-showNum) });
			}else if( i == len - 2 ){
				i++;
				$wrapper.stop().animate({ marginLeft: showWidth - w*len });
			}
		});
	};

	/**
	 * navbar初始化，调用点击事件
	 */
	var onNavbarRollInit = function(index){
		var $oRow = $(".show-wrapper div.row");
		var len = $oRow.length;
		var w = $oRow.eq(0).width();
		$(".show-wrapper").css( "width", w*len + 'px' );  // width根据.row的个数定义
		var showWidth = $("#showContainer").width()-5;		// 不知道为什么会有13px的差距 13px=>5px
		var showNum = Math.floor( showWidth / w );
		var W = w*(index+1)-showWidth;
		if(index >= showNum){
			$(".show-wrapper").css({ marginLeft: -W });
		}
		onNavbarRoll($(".arrow-left"),$(".arrow-right"),$(".show-wrapper"),showNum,w,len,index,showWidth);
	}

	/**
	 * 请求患者基本信息成功后的回调函数
	 */
	var getRevisedInfoParamsCallback = function(data,params,curInfo,paramsRecord){
		params.patientName = data.PatientInfo.userName;
		params.imgSrc = "page/followup/imgs/comm/" + ( data.PatientInfo.gender == "F" ? "girl":"boy" ) + ".png";
		params.gender = data.PatientInfo.gender;
		params.taskId = curInfo.taskId;
		$outPatientServers.ajaxTasks(getTasksCallback,params);
		
		//wxf 处理增加生长发育打通到量表里面
		var paramsRecordData=paramsRecord;
		
		if(JSON.stringify(paramsRecordData)!= "{}"){
			var userId="";
			paramsRecordData.userId=params.patientId;
			$outPatientServers.addGrowthANDRecord(params.patientId,paramsRecordData);
		}
		
    	$bb.toastShow("保存成功！",3000);
	}
	/**
	 * 保存问卷成功后的回调方法
	 */
	var getSaveCallback = function(params,curInfo,paramsRecord){
		$outPatientServers.getRevisedInfoParams(params,curInfo,getRevisedInfoParamsCallback,paramsRecord);
	}
	/**
	 * 保存随访问卷答案
	 */
	var onSaveQuestion = function(){
		if( $validate.init() ){
			var data = $(this).data("params");
			$outPatientServers.ajaxSaveQuestion(data.data,data.params,data.curInfo,getSaveCallback);
		}
	}
	/**
	 * 改变随访日期时，年龄随之改变
	 */
	var changeAgeByFinishDate = function(){
		var time = $(this).val();
		if( time ){
	    	var birthday = $("#followupAge").attr("birthday");
	    	var expectedDay = $("#followupAge").attr("expectedDay");
	    	var pregnancyDay = $("#followupAge").attr("pregnancyDay");
	    	var paramsAge = {
	    		"birthday":birthday,
	    		"expectedDay":expectedDay,
	    		"pregnancyDay":pregnancyDay
	    	}
	    	var followupAge = $outPatientServers.getFollowupAge(paramsAge,time);
	    	$("#followupAge .control-label").html(followupAge.ageLabel);
	    	$("#followupAge p[name=followupAge]").html(followupAge.age);
	    	if( $("#followupActualAge").length > 0 && followupAge.actualAgeLabel && followupAge.actualAge ){
	    		$("#followupActualAge .control-label").html(followupAge.actualAgeLabel);
	    		$("#followupActualAge p[name=followupActualAge]").html(followupAge.actualAge);
	    	}
    	}else{
	    	$("#followupAge p[name=followupAge]").html("");
	    	$("#followupActualAge p[name=followupActualAge]").html("");
    	}
	}
	/**
	 * 锚点事件
	 */
	var anchorMenuEvent = function(){
		$("#anchorMenu .anchor-menu-fold").click(function(){
        	$("#anchorMenu .anchor-menu-unfold").show();
        	$("#anchorMenu .anchor-menu-fold").hide();
        });
        $("#anchorMenu .anchor-menu-unfold .anchor-menu-close").click(function(){
        	$("#anchorMenu .anchor-menu-fold").show();
        	$("#anchorMenu .anchor-menu-unfold").hide();
        });
        $("#anchorMenu .anchor-menu-unfold ul li").click(function(){
        	$(this).addClass("active").siblings().removeClass("active");
        });
		var obj = document.getElementById("content-main");   
		if( obj.scrollHeight > obj.clientHeight || obj.offsetHeight > obj.clientHeight){ 
			$("#anchorMenu").css({"right":"27px"});
		}else{
			$("#anchorMenu").css({"right":"20px"});
		}
	}
	/**
	 * 请求问卷成功后的回调方法
	 */
	var getQuestionCallback = function(data,params,curInfo,addTaskInfo){
		$outPatientUi.followUpInit({
        	id: "followUpInfo",
        	list: data.questiones,	  // 问卷
            status: curInfo.status,
            task: data.task,	 // 随访指导
            ageRelate:params,	// 随访指导里的随访年龄相关数据
            sampleList:data.sampleList
        });
        /* 改变随访日期时，年龄随之改变 begin */
        $("input[name=finishDate]").unbind("change");
        $("input[name=finishDate]").change(changeAgeByFinishDate);
        /* end 改变随访日期时，年龄随之改变 */
        $questionUi.init({
        	id: "questions",
        	status: curInfo.status,
            list: data.questiones,	  // 问卷
            values: $comm.handleValue(data.patientInfo,data.values),
            initParams:{
            	"queueId":params.followQueueId
            }
        });
        $questionEvent.init({
        	"getGrowth":{
        		"patientId":data.oprInfo.patientId,
	        	"preTaskId":curInfo.preTaskId,
	        	"followQueueId":params.followQueueId,
            	"gender":params.gender
        	},
        	"getTextareaAssess":{
        		"userId":params.patientId,
        		"taskId":curInfo.taskId
        	}
        });
        $outPatientUi.anchorMenuInit({
        	"id":"anchorMenu",
        	"list":data.questiones
        });
        // 锚点事件
        anchorMenuEvent();
        $attention.init();
        $('.validatebox').data("attentionFun",$attention.blurInit);	// 校验之前提示警告
        $validate.blurInit();
		$.extend(curInfo,{"addTaskFlag":addTaskInfo.addTaskFlag});
		var params02 = {
			callback1:onPatientDelect,
			callback2:onSaveQuestion,
			callback3:onChangeCanWrite,
			callback4:onAddTask,
			callback5:onPrintClick,
			callback6:onCheckClick,
			callback7:onResetData,
			callback8:onDeleteTemporary,
			callback9:onLookPicture,
			params1:$outPatientServers.getDeleteParams(),
			params2:{data:data,params:params,curInfo:curInfo},
			params3:{data:data,params:params,curInfo:curInfo,addTaskInfo:addTaskInfo},
			params4:{params:params,afterTaskId:addTaskInfo.afterTaskId,fun:$outPatientServers.ajaxTasks,getTasksCallback:getTasksCallback},
			params5:{data:data,params:params,curInfo:curInfo},
			params6:{data:data,params:params,curInfo:curInfo},
			params7:{data:data,params:params,curInfo:curInfo,addTaskInfo:addTaskInfo},
			params8:{params:params,afterTaskId:addTaskInfo.afterTaskId,fun:$outPatientServers.ajaxTasks,deleteTasksCallback:deleteTasksCallback,taskId:curInfo.taskId},
			params9:{oprInfo:data.oprInfo}
		};
		var topbars = $outPatientServers.handleBtnGroup(curInfo,params02);
		$bb.toolbar(topbars);
	}
	var onAddTask = function(){
		var data = $(this).data("params");
		$bb.toastConfirmShow($outPatientServers.ajaxAddTask,data,"确定添加临时随访?");
	}
	/**
	 * 点击修改按钮将问卷转化为可写状态
	 */
	var onChangeCanWrite = function(){
		var data = $(this).data("params");
    	data.curInfo.status = "default";
		getQuestionCallback(data.data,data.params,data.curInfo,data.addTaskInfo);
	}
	/**
	 * 切换随访任务
	 */	
	var onTaskSelect = function(){
		var data = $(this).data();
		var curInfo = data.curInfo;
		var index;
		if( data.flag ){
			index = 0;
			clickTaskFlag = true;
			$(".show-wrapper").css({"marginLeft":0});
		}else{
			index = $(this).index();
		}
		$(".show-wrapper > div.row").eq(index).addClass("active").siblings().removeClass("active");
		var curData = data.rows[index];
		curInfo.taskId = curData.taskId;
		curInfo.taskStatus = curData.taskStatus;
		curInfo.status = $outPatientServers.curTaskStatus( curData.taskStatus );
		curInfo.seqNo = curData.seqNo;
		curInfo.preTaskId = curData.preTaskId;
		curInfo.auditStatus = curData.auditStatus;
		curInfo.isTemporary = $(this).text().indexOf("临时随访") != -1?1:0;
		// 若点击的任务是审核状态，则表单的titlt也要给出待审核提示。
		if( curData.auditStatus == "4" ){
			$("#followUpTit .tit").html('<i class="fa fa-question-circle" aria-hidden="true" data-toggle="tooltip" data-placement="left" title="内容待审核"></i>' + data.params.queuename);
		}else{
			$("#followUpTit .tit").html(data.params.queuename);
		}
		$(function(){ $('[data-toggle="tooltip"]').tooltip(); });
		$outPatientServers.ajaxQuestion(data.params,curInfo,getQuestionCallback,data.addTaskInfo);
	}
	/**
	 * 请求任务列表成功后的回调方法
	 */
	var getTasksCallback = function(rows,params){
		$outPatientUi.taskBabycardInit({	// 个人信息
			id:"taskBabycard",
			list: params,
		});
		var curInfo = $outPatientServers.getCurInfo(rows,params.taskId);
		refreshTasksUi(rows,curInfo);
		var addTaskInfo = $outPatientServers.getAddTaskInfo(rows);	// 添加临时随访
		var index = $outPatientServers.getTaskIndexByTaskId(rows,curInfo.taskId);
		onNavbarRollInit(index);
		$(".show-wrapper > div.row").unbind("click");
		$(".show-wrapper > div.row").data({rows: rows, curInfo: curInfo, params :params, addTaskInfo:addTaskInfo});
		$(".show-wrapper > div.row").click(onTaskSelect);
		$(".show-wrapper > div.row").eq(index).click();
		// 点击taskBabycard跳转到建档（此页面的建档）
		$("#taskBabycard").unbind("click");
		$("#taskBabycard").data({flag:true, rows: rows, curInfo: curInfo, params :params, addTaskInfo:addTaskInfo});
		$("#taskBabycard").click(onTaskSelect);
	};
	/**
	 * 删除任务列表成功后的回调方法
	 */
	var deleteTasksCallback = function(rows,params){
		$outPatientUi.taskBabycardInit({	// 个人信息
			id:"taskBabycard",
			list: params,
		});
		params.taskId = rows[rows.length-1].taskId;
		var curInfo = $outPatientServers.getCurInfo(rows,params.taskId);
		refreshTasksUi(rows,curInfo);
		var addTaskInfo = $outPatientServers.getAddTaskInfo(rows);	// 添加临时随访
		var index = $outPatientServers.getTaskIndexByTaskId(rows,curInfo.taskId);
		onNavbarRollInit(index);
		$(".show-wrapper > div.row").unbind("click");
		$(".show-wrapper > div.row").data({rows: rows, curInfo: curInfo, params :params, addTaskInfo:addTaskInfo});
		$(".show-wrapper > div.row").click(onTaskSelect);
		$(".show-wrapper > div.row").eq(index).click();
		// 点击taskBabycard跳转到建档（此页面的建档）
		$("#taskBabycard").unbind("click");
		$("#taskBabycard").data({flag:true, rows: rows, curInfo: curInfo, params :params, addTaskInfo:addTaskInfo});
		$("#taskBabycard").click(onTaskSelect);
	};
	event.getTasksCallback = function(rows,params){
		getTasksCallback(rows,params);
	};
	/**
	 * 删除患者
	 */
	var onPatientDelect = function(){
		var params = $(this).data("params");
		$bb.toastConfirmShow($outPatientServers.ajaxDelPatient,params,"确定从该队列中删除患者?");
	}
	event.onPatientDelect = function(){
		onPatientDelect();
	}
	/**
	 * 重置患者问卷数据
	 */
	var onResetData = function(){
		var params = $(this).data("params");
		$bb.toastConfirmShow(function(){
			params.curInfo.status = "default";
			$.each(Object.keys(params.data.values),function(index,b){
				if(params.data.values[b].indexOf("[") != -1&&b.indexOf("sf") != 0){
					params.data.values[b] = "[]" ;
				}else{
					delete params.data.values[b];
				}
			})
			params.data.questiones.map(function(a,index1){
				a.map(function(b){
					b.children.map(function(c){
						if(index1 == 0&&c.id != "gfy_xsekgwejd_yc"&&c.id != "gfy_xsekgwejd_cc"){
							c.val = "";
						}
						if(c.list instanceof Array){
							c.list.map(function(d,index){
								var ids = "gfyxsek_sf_nkfzl,sfzhidaoAyd01";
								d.flag = index == 0&&ids.indexOf(c.id) == -1?true:false;
								var onChecked = "16TS0I20ABeRmzqzOQ5w,160j7QDK3PHoHaXxYBeU,16xRRfs8r2dtBrcQI2ce,164fXgfwyBWUyrSM1GX5,16wIVFIjTWxJsMHe2oK7,16KErFgFn8FzF5Xto6ld,16bhBmWbQMoMuTZLAizC,16vmgmL1jdBpKRfX3eME,16V31a5NUr64VaKXNfeM,16Q2W6KlrGNUZ8me5D99,167hUV1XU7r7Jf85p2b3";
								var towChecked = "16Q2W6KlrGNUZ8me5D99";
								var ids2 = "gfy_xsekgwejd_yjzym,sf3_ymjzzd,sf4_ymjzzd,sf6_ymjzzd,sf18_ymjzzd,sf21_ymjzzd,sf8_ymjzzd,gfy_xsekgwejd_yjzym"
								 if(ids2.indexOf(c.id) != -1 &&(index == 0||(onChecked.indexOf(params.data.task.ptTaskId) != -1&&index==1)||(towChecked.indexOf(params.data.task.ptTaskId) != -1&&index==2))){
									d.flag = true;
								}
								if(c.relationId){
									d.flag = false;
									c.valText = "";
								}
							})
							
						}
						if(c.children instanceof Array){
							c.children.map(function(e){
								if(e.list instanceof Array){
									e.list.map(function(f,index){
										f.flag = index == 0&&index1 == 1?true:false;
									})
								}
								e.val = "";
							})
						}
						

						if(index1 == 1){
							var ids = "sf";
							if((c.id+"").indexOf(ids) == -1||c.id == "sf24_tj"||c.id.indexOf("qtzdjy") != -1||c.id.indexOf("ksswzhnl") != -1){
								c.val = "";
							}
							
						}
					})
				})
			})
			console.info(params.data)
			getQuestionCallback(params.data,params.params,params.curInfo,params.addTaskInfo);
		},params,"确定清除本条填写数据?");
	}
	event.onResetData = function(){
		onResetData();
	}
	/**
	 * 重置患者问卷数据
	 */
	var onDeleteTemporary = function(){
		var params = $(this).data("params");
		$bb.toastConfirmShow($outPatientServers.ajaxDeleteTemporary,params,"确定删除当前临时随访问卷?");
	}
	event.onDeleteTemporary = function(){
		onDeleteTemporary();
	}
	
	return event;
});